package com.hjzd.ai.smartpractice.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

public class AudioStreamHandlerThread extends Thread {
    private static final Logger logger = LoggerFactory.getLogger(AudioStreamHandlerThread.class);
    private boolean stop = false;

    @Override
    public void run() {
        while (!stop){
            for (Map.Entry<WebSocketSession, ConcurrentLinkedQueue<byte[]>> entry : SessionManager.sessionOpenaiInfoCache.entrySet()) {
                WebSocketSession session = entry.getKey();
                ConcurrentLinkedQueue<byte[]> openaiInfoQueue = entry.getValue();
                byte[] openaiAudioBin;
                while ((openaiAudioBin = openaiInfoQueue.poll()) != null) {
                    if (openaiAudioBin.length > 0) {
                        try {
                            logger.info("AudioStreamHandlerThread, send audioBin:{}", openaiAudioBin.length);
                            session.sendMessage(new BinaryMessage(openaiAudioBin));

                        } catch (IOException e) {
                            logger.error(">>>> 认知重塑openai音频ws发送异常, 错误信息=", e);
                        }
                    }
                }
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void setStop(boolean stop) {
        this.stop = stop;
    }
}
